<?php
/**
 * Class model that provides the base functionality to manage purposes
 *
 * @author Gonzalez Federico, Viera Leonel
 * @package Protoweb
 * @subpackage model
 */
class Purpose extends PwModel
{

    public $slug       = null;
    public $label      = null;
    public $dbDatatype = null;
    public $templates  = null;


    public static function getAll()
    {
        // get CodeIngiter instace
        $CI =& get_instance();

        // get purposes from folder
        $purposes = scandir($CI->config->item('purposes_path'));

        // remove '.' and '..' entries and reconstruct array index
        $purposes = array_diff($purposes, array('.','..'));
        $purposes = array_values($purposes);

        // build purposes array
        $purposesArray = array();
        foreach ($purposes as $purposeName) {
            $purposeObj = new Purpose(basename($purposeName,'.json'));
            array_push($purposesArray, $purposeObj);
        }

        return $purposesArray;
    }

    public static function getFilePath($slug)
    {
        // get CodeIngiter instace
        $CI =& get_instance();

        return $CI->config->item('purposes_path') . $slug . '.json';   
    } 

    public function __construct($slug)
    {
        // get CodeIngiter instace
        $CI =& get_instance();

        // get purpose file contents
        $purpose = file_get_contents($CI->config->item('purposes_path') . $slug . '.json');

        if ($purpose) {

            // parse purpose and assign values to object properties
            $purpose          = json_decode($purpose,true);
            $this->slug       = $slug;
            $this->label      = $purpose['label'];
            $this->dbDatatype = $purpose['dbdatatype'];
            $this->templates  = $purpose['templates'];

            return $this;
        }
        else {
            return null;
        }
    }
} // class Purpose

/* End of file purpose.php */
/* Location: ./application/models/purpose.php */
